import Stomp from 'stompjs';

class ChatService {
    constructor(config) {
        this.config = config;
        this.stompClient = null;
        this.init();
    }

    init() {
        const socket = uni.connectSocket({
            url: this.config.url,
            header: {
                satoken: this.config.satoken
            },
            success: () => {
                console.log('WebSocket 连接成功');
                this.stompClient = Stomp.over(socket);
                this.stompClient.connect({}, () => {
                    console.log('STOMP 连接成功');
                });
            },
            fail: (err) => {
                console.error('WebSocket 连接失败', err);
            }
        });
    }

    subscribe(destination, callback) {
        if (this.stompClient) {
            this.stompClient.subscribe(destination, (message) => {
                callback(message.body);
            });
        }
    }

    sendMessage(destination, message) {
        if (this.stompClient) {
            this.stompClient.send(destination, {}, message);
        }
    }
}

export default ChatService;